package com.ffk.wiki.service;

import com.ffk.wiki.Util.CopyUtil;
import com.ffk.wiki.Util.SnowFlake;
import com.ffk.wiki.domain.Category;
import com.ffk.wiki.domain.CategoryExample;
import com.ffk.wiki.mapper.CategoryMapper;
import com.ffk.wiki.req.CategoryQueryReq;
import com.ffk.wiki.req.CategorySaveReq;
import com.ffk.wiki.resp.CategoryResp;
import com.ffk.wiki.resp.PageResp;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SnowFlake snowFlake;

    public List<Category> getAll(){
        return categoryMapper.selectByExample(null);
    }

    public List<CategoryResp> all(){
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryResp> respList= CopyUtil.copyList(categoryList,CategoryResp.class);
        return respList;
    }

    public PageResp<CategoryResp> getCategory(CategoryQueryReq categoryReq){
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        // 这里查出来的是Category，里面字段和表字段是一样的，但是我们返回出去的是响应封装类，因此要转化一下
        PageHelper.startPage(categoryReq.getPage(),categoryReq.getSize());// 1代码从第几页查，3代表每页显示3条数据.
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryResp> respList= CopyUtil.copyList(categoryList,CategoryResp.class);
        PageInfo<Object> pageInfo=new PageInfo<>();
        PageResp pageResp=new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);
        return pageResp;
    }

    /**
     * 更新和添加方法
     */
    public void save(CategorySaveReq req) {
        Category category = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            category.setId(snowFlake.nextId());
//            category.setDocCount(0);
//            category.setViewCount(0);
//            category.setVoteCount(0);
            categoryMapper.insert(category);
        } else {
            // 更新
            categoryMapper.updateByPrimaryKey(category);
        }
    }

    //删除方法
    public void delete(Long id) {
        categoryMapper.deleteByPrimaryKey(id);
    }
}
